package websocket;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.json.JSONObject;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import domain.User;
import service.IMessageService;
import service.IRoomMemberService;
import service.ISocketService;

/**
 *
 * @author lzk
 */
@Component
public class SystemWebSocketHandler extends TextWebSocketHandler {
	private static Logger log = Logger.getLogger(SystemWebSocketHandler.class);

	@Resource
	private ISocketService socketServer;
	@Resource
	private IMessageService messageService;
	@Resource
	private IRoomMemberService roomMemberService;
	
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    	log.info("connect to the websocket success......");
    	
    	User user = (User) session.getAttributes().get("user");
    	
    	if (user == null) {
    		return;
    	}
    	
    	socketServer.registerSocket(user.getUserId(), session);
    }

    @Override
    public void handleMessage(WebSocketSession wss, WebSocketMessage<?> wsm) throws Exception {
    	JSONObject json = new JSONObject((String)wsm.getPayload());
    	
    	User user = (User) wss.getAttributes().get("user");
    	
    	if (user == null) {
    		return;
    	}
    	
    	messageService.analysis(json, user.getUserId());
    }

    @Override
    public void handleTransportError(WebSocketSession wss, Throwable thrwbl) throws Exception {
        if(wss.isOpen()){
            wss.close();
        }
        
        log.info(thrwbl);
        log.info("websocket connection closed......");

        afterClose(wss);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession wss, CloseStatus cs) throws Exception {
    	log.info("websocket connection closed......");
    	
    	 afterClose(wss);
    }
    
    private void afterClose(WebSocketSession wss) {
    	log.info("process log out socket");
    	
    	User user = (User) wss.getAttributes().get("user");
     	
     	if (user == null) {
     		return;
     	}
     	
     	log.info("log out socket success");
     	
     	socketServer.logoutSocket(user.getUserId());
		roomMemberService.logoutUser(user);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
    
}
